import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import warnings
warnings.filterwarnings("ignore")
import matplotlib
%matplotlib inline
import fbprophet #for time series modeling and forecasting
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
import plotly.offline as py
py.init_notebook_mode()
import plotly.graph_objects as go
import plotly.express as px
plt.style.use('fivethirtyeight')
matplotlib.rcParams['axes.labelsize'] = 14
matplotlib.rcParams['xtick.labelsize'] = 12
matplotlib.rcParams['ytick.labelsize'] = 12
matplotlib.rcParams['text.color'] = 'k'
DAL = pd.read_csv('DAL.csv') #Delta
AAL = pd.read_csv('AAL.csv') #American
LUV = pd.read_csv('LUV.csv') #SouthWest
UAL = pd.read_csv('UAL.csv') #United
AAL.tail(5)
plt.figure(figsize = (24,12))
plt.plot(range(DAL.shape[0]),(DAL['Low']+DAL['High'])/2.0, 'b-', label = 'Delta')
plt.plot(range(AAL.shape[0]),(AAL['Low']+AAL['High'])/2.0, 'r-', label = 'American')
plt.plot(range(LUV.shape[0]),(LUV['Low']+LUV['High'])/2.0, 'g-', label = 'SouthWest')
plt.plot(range(UAL.shape[0]),(UAL['Low']+UAL['High'])/2.0, 'y-', label = 'United')
plt.xticks(range(0,DAL.shape[0],500),DAL['Date'].loc[::500],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in the 4 Airlines Stock Prices over 13 year')
plt.legend();
#Data Visualization
##Exploring the patterns occuring over time
plt.figure(figsize = (18,9))
plt.plot(range(DAL.shape[0]),(DAL['Low']+DAL['High'])/2.0)
plt.xticks(range(0,DAL.shape[0],500),DAL['Date'].loc[::500],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in Delta Airlines Stock Prices over 13 year')
plt.show()
plt.figure(figsize = (18,9))
plt.plot(range(AAL.shape[0]),(AAL['Low']+AAL['High'])/2.0,'r')
plt.xticks(range(0,AAL.shape[0],500),AAL['Date'].loc[::500],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in American Airlines Stock Prices over 13 year')
plt.show()
plt.figure(figsize = (18,9))
plt.plot(range(LUV.shape[0]),(LUV['Low']+LUV['High'])/2.0,'g')
plt.xticks(range(0,LUV.shape[0],500),LUV['Date'].loc[::500],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in SouthWest Airlines Stock Prices over 13 year')
plt.show()
plt.figure(figsize = (18,9))
plt.plot(range(UAL.shape[0]),(UAL['Low']+UAL['High'])/2.0,'y')
plt.xticks(range(0,UAL.shape[0],500),UAL['Date'].loc[::500],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in United Airlines Stock Prices over 13 year')
plt.show()
DAL['Date'] = pd.to_datetime(DAL['Date'])
DAL['Year'] = DAL['Date'].dt.year
AAL['Date'] = pd.to_datetime(AAL['Date'])
AAL['Year'] = AAL['Date'].dt.year
DAL.tail(5)
LUV['Date'] = pd.to_datetime(LUV['Date'])
LUV['Year'] = LUV['Date'].dt.year
UAL['Date'] = pd.to_datetime(UAL['Date'])
UAL['Year'] = UAL['Date'].dt.year
UAL.head(5)
from pandas import *
xls = ExcelFile('Shares.xlsx')
data = xls.parse(xls.sheet_names[0])
print(data['UAL'].to_dict())
# Yearly average number of shares outstanding for Delta and American Airlines
##For year 2020 only first quarter data
dal_shares = {2020: 637e6, 2019: 653e6, 2018: 694e6, 2017: 723e6, 2016: 755e6, 2015: 804e6, 2014: 845e6,
2013: 858e6, 2012: 850e6, 2011: 844e6, 2010: 843e6, 2009: 827e6, 2008: 468e6, 2007: 395e6}
aal_shares = {2020: 426e6, 2019: 444e6, 2018: 466e6, 2017: 492e6, 2016: 556e6, 2015: 687e6, 2014: 734e6,
2013: 280e6, 2012: 249e6, 2011: 125e6, 2010: 333e6, 2009: 294e6, 2008: 259e6, 2007: 267e6}
luv_shares = {2020: 515e6, 2019: 539e6, 2018: 574e6, 2017: 603e6, 2016: 633e6, 2015: 669e6, 2014: 696e6,
2013: 718e6, 2012: 757e6, 2011: 775e6, 2010: 747e6, 2009: 741e6, 2008: 739e6, 2007: 768e6}
ual_shares = {2020: 249e6, 2019: 260e6, 2018: 277e6, 2017: 304e6, 2016: 330e6, 2015: 377e6, 2014: 390e6,
2013: 391e6, 2012: 331e6, 2011: 383e6, 2010: 253e6, 2009: 151e6, 2008: 127e6, 2007: 151e6}
# Take Dates from index and move to Date column
DAL.reset_index(level=0, inplace = True)
# Take Dates from index and move to Date column
AAL.reset_index(level=0, inplace = True)
# Take Dates from index and move to Date column
LUV.reset_index(level=0, inplace = True)
# Take Dates from index and move to Date column
UAL.reset_index(level=0, inplace = True)
#Calculate Market Capitalization
#Delta
DAL['cap'] = 0
# Calculate market cap for all years
for i, year in enumerate(DAL['Year']):
# Retrieve the shares for the year
shares = dal_shares.get(year)
# Update the cap column to shares times the price
DAL.ix[i, 'cap'] = shares * DAL.ix[i, 'Adj Close']
#American
AAL['cap'] = 0
# Calculate market cap for all years
for i, year in enumerate(AAL['Year']):
# Retrieve the shares for the year
shares = aal_shares.get(year)
# Update the cap column to shares times the price
AAL.ix[i, 'cap'] = shares * AAL.ix[i, 'Adj Close']
#SouthWest
LUV['cap'] = 0
# Calculate market cap for all years
for i, year in enumerate(LUV['Year']):
# Retrieve the shares for the year
shares = luv_shares.get(year)
# Update the cap column to shares times the price
LUV.ix[i, 'cap'] = shares * LUV.ix[i, 'Adj Close']
#United
UAL['cap'] = 0
# Calculate market cap for all years
for i, year in enumerate(UAL['Year']):
# Retrieve the shares for the year
shares = ual_shares.get(year)
# Update the cap column to shares times the price
UAL.ix[i, 'cap'] = shares * UAL.ix[i, 'Adj Close']
UAL.head(5)
# Merge the two datasets and rename the columns
airlines1 = DAL.merge(AAL, how='inner', on='Date')
airlines2 = LUV.merge(UAL, how='inner',on='Date')
#Changing the names for merge
airlines1.rename(columns={'cap_x': 'DAL_cap', 'cap_y': 'AAL_cap'}, inplace=True)
airlines2.rename(columns={'cap_x': 'LUV_cap', 'cap_y': 'UAL_cap'}, inplace=True)
#from functools import reduce
#data_frames= [DAL, AAL, LUV, UAL]
#airlines = reduce(lambda left, right: pd.merge(left, right,on=['Date'],how='inner'),data_frames)
print(airlines1.columns)
print(airlines2.columns)
airlines = airlines1.merge(airlines2, how='inner', on='Date')
# Select only the relevant columns
airlines = airlines.ix[:, ['Date', 'DAL_cap', 'AAL_cap','LUV_cap','UAL_cap']]
# Divide to get market cap in billions of dollars
airlines['DAL_cap'] = airlines['DAL_cap'] / 1e9
airlines['AAL_cap'] = airlines['AAL_cap'] / 1e9
airlines['LUV_cap'] = airlines['LUV_cap'] / 1e9
airlines['UAL_cap'] = airlines['UAL_cap'] / 1e9
airlines.head()
plt.figure(figsize=(24, 12))
plt.plot(airlines['Date'], airlines['DAL_cap'], 'b-', label = 'DAL')
plt.plot(airlines['Date'], airlines['AAL_cap'], 'r-', label = 'AAL')
plt.plot(airlines['Date'], airlines['LUV_cap'], 'g-', label = 'LUV')
plt.plot(airlines['Date'], airlines['UAL_cap'], 'y-', label = 'UAL')
plt.xlabel('Date'); plt.ylabel('Market Cap (Billions $)'); plt.title('Market Cap of Delta, America, Southwest and United Airlines')
plt.legend();
plt.figure(figsize=(10, 8))
plt.plot(airlines['Date'], airlines['DAL_cap'], 'b-', label = 'DAL')
plt.plot(airlines['Date'], airlines['LUV_cap'], 'g-', label = 'LUV')
plt.xlabel('Date'); plt.ylabel('Market Cap (Billions $)'); plt.title('Market Cap of Delta and Southwest Airlines')
plt.legend();
plt.figure(figsize=(10, 8))
plt.plot(airlines['Date'], airlines['AAL_cap'], 'r-', label = 'AAL')
plt.plot(airlines['Date'], airlines['UAL_cap'], 'y-', label = 'UAL')
plt.xlabel('Date'); plt.ylabel('Market Cap (Billions $)'); plt.title('Market Cap of America and United Airlines')
plt.legend();
American Airlines briefly surpassed Delta Airlines in market cap in 2015. From 2008, financial crisis onwards AA couldn't perform better than DA.
It is also worth noticing in the year 2020, though both industry has seen a decline due to COVID-19 pandemic, but the Delta Airlines stocks and market cap has plummeted more than American Airlines.
* Can this be a twist or an opportunity for American Airlines?
# Find the first and last time LUV was valued higher than DAL
first_date = airlines.ix[np.min(list(np.where(airlines['LUV_cap'] > airlines['DAL_cap'])[0])), 'Date']
last_date = airlines.ix[np.max(list(np.where(airlines['LUV_cap'] > airlines['DAL_cap'])[0])), 'Date']
print("LUV was valued higher than DAL on {} and {}.".format(first_date.date(), last_date.date()))
# Find the first and last time AAL was valued higher than UAL
first_date = airlines.ix[np.min(list(np.where(airlines['AAL_cap'] > airlines['UAL_cap'])[0])), 'Date']
last_date = airlines.ix[np.max(list(np.where(airlines['AAL_cap'] > airlines['UAL_cap'])[0])), 'Date']
print("AAL was valued higher than UAL on {} and {}.".format(first_date.date(), last_date.date()))
Note
# Prophet requires columns ds (Date) and y (value)
DAL = DAL.rename(columns={'Date': 'ds', 'cap': 'y'})
AAL = AAL.rename(columns={'Date': 'ds', 'cap': 'y'})
LUV = LUV.rename(columns={'Date': 'ds', 'cap': 'y'})
UAL = UAL.rename(columns={'Date': 'ds', 'cap': 'y'})
# Put market cap in billions
DAL['y'] = DAL['y'] / 1e9
AAL['y'] = AAL['y'] / 1e9
LUV['y'] = LUV['y'] / 1e9
UAL['y'] = UAL['y'] / 1e9
Entire data model
# Make the prophet models and fit on the data
# changepoint_prior_scale can be changed to achieve a better fit
#D_Model1 = Prophet(changepoint_prior_scale=0.15, changepoints=['2020-03-16', '2020-05-15'])
D_Model1 = Prophet(changepoint_prior_scale=0.20)
D_Model1.fit(DAL)
##For next 60 days
dal_forecast = D_Model1.make_future_dataframe(periods=60, freq='D')
# Make predictions
dal_forecast = dal_forecast[dal_forecast['ds'].dt.dayofweek < 5]
dal_forecast = D_Model1.predict(dal_forecast)
# Repeat for the 3 airlines data
#A_Model1 = Prophet(changepoint_prior_scale=0.15, changepoints=['2020-03-16','2020-04-15'], n_changepoints=10)
A_Model1 = Prophet(changepoint_prior_scale=0.20)
A_Model1.fit(AAL);
L_Model1 = Prophet(changepoint_prior_scale=0.20)
L_Model1.fit(LUV);
U_Model1 = Prophet(changepoint_prior_scale=0.20)
U_Model1.fit(UAL);
#Make Predictions
aal_forecast = A_Model1.make_future_dataframe(periods=60, freq='D')
aal_forecast = aal_forecast[aal_forecast['ds'].dt.dayofweek < 5]
aal_forecast = A_Model1.predict(aal_forecast)
luv_forecast = L_Model1.make_future_dataframe(periods=60, freq='D')
luv_forecast = luv_forecast[luv_forecast['ds'].dt.dayofweek < 5]
luv_forecast = L_Model1.predict(luv_forecast)
ual_forecast = U_Model1.make_future_dataframe(periods=60, freq='D')
ual_forecast = ual_forecast[ual_forecast['ds'].dt.dayofweek < 5]
ual_forecast = U_Model1.predict(ual_forecast)
def make_comparison_dataframe(historical, forecast):
return forecast.set_index('ds')[['yhat', 'yhat_lower', 'yhat_upper']].join(historical.set_index('ds'))
def calculate_forecast_errors(df, prediction_size):
df = df.copy()
df['e'] = df['y'] - df['yhat']
df['p'] = 100 * df['e'] / df['y']
predicted_part = df[-prediction_size:]
error_mean = lambda error_name: np.mean(np.abs(predicted_part[error_name]))
return {'MAPE': error_mean('p'), 'MAE': error_mean('e')}
#Plotting the forecast for the airlines
fig1 = go.Figure()
fig2 = go.Figure()
fig3 = go.Figure()
fig4 = go.Figure()
fig1 = plot_plotly(D_Model1, dal_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig1.update_layout(title = 'Market cap forecast of Delta')
cmp_d = make_comparison_dataframe(DAL, dal_forecast)
cmp_d.tail()
for err_name, err_value in calculate_forecast_errors(cmp_d, 60).items():
print(err_name, err_value)
fig2 = plot_plotly(L_Model1, luv_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig2.update_layout(title = 'Market cap forecast of Southwest')
cmp_s = make_comparison_dataframe(LUV, luv_forecast)
#cmp_df.tail()
for err_name, err_value in calculate_forecast_errors(cmp_s, 60).items():
print(err_name, err_value)
fig3 = plot_plotly(A_Model1, aal_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig3.update_layout(title = 'Market cap forecast of American')
cmp_a = make_comparison_dataframe(AAL, aal_forecast)
#cmp_df.tail()
for err_name, err_value in calculate_forecast_errors(cmp_a, 60).items():
print(err_name, err_value)
fig4 = plot_plotly(U_Model1, ual_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig4.update_layout(title = 'Market cap forecast of United')
cmp_u = make_comparison_dataframe(UAL, ual_forecast)
#cmp_df.tail()
for err_name, err_value in calculate_forecast_errors(cmp_u, 60).items():
print(err_name, err_value)
#Hold-out 30 observations
size = 30
train_df = DAL[:-size]
D_Model4 = Prophet(changepoint_prior_scale=0.20)
D_Model4.fit(train_df)
train_df = AAL[:-size]
A_Model4 = Prophet(changepoint_prior_scale=0.20)
A_Model4.fit(train_df)
train_df = LUV[:-size]
L_Model4 = Prophet(changepoint_prior_scale=0.20)
L_Model4.fit(train_df)
train_df = UAL[:-size]
U_Model4 = Prophet(changepoint_prior_scale=0.20)
U_Model4.fit(train_df)
##For next 60 days
dal3_forecast = D_Model4.make_future_dataframe(periods=60, freq='D')
# Make predictions
dal3_forecast = dal3_forecast[dal3_forecast['ds'].dt.dayofweek < 5]
dal3_forecast = D_Model4.predict(dal3_forecast)
aal3_forecast = A_Model4.make_future_dataframe(periods=60, freq='D')
# Make predictions
aal3_forecast = aal3_forecast[aal3_forecast['ds'].dt.dayofweek < 5]
aal3_forecast = A_Model4.predict(aal3_forecast)
luv3_forecast = L_Model4.make_future_dataframe(periods=60, freq='D')
# Make predictions
luv3_forecast = luv3_forecast[luv3_forecast['ds'].dt.dayofweek < 5]
luv3_forecast = L_Model4.predict(luv3_forecast)
ual3_forecast = U_Model4.make_future_dataframe(periods=60, freq='D')
# Make predictions
ual3_forecast = ual3_forecast[ual3_forecast['ds'].dt.dayofweek < 5]
ual3_forecast = U_Model4.predict(ual3_forecast)
#Plotting the forecast for the airlines
fig1 = go.Figure()
fig2 = go.Figure()
fig3 = go.Figure()
fig4 = go.Figure()
fig1 = plot_plotly(D_Model4, dal3_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig1.update_layout(title = 'Market cap forecast of Delta')
fig2 = plot_plotly(L_Model4, luv3_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig2.update_layout(title = 'Market cap forecast of Southwest')
fig3 = plot_plotly(A_Model4, aal_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig3.update_layout(title = 'Market cap forecast of American')
fig4 = plot_plotly(U_Model4, ual_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig4.update_layout(title = 'Market cap forecast of United')
cmp_d3 = make_comparison_dataframe(DAL, dal3_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_d3, 60).items():
print(err_name, err_value)
cmp_a3 = make_comparison_dataframe(AAL, aal3_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_a3, 60).items():
print(err_name, err_value)
cmp_l3 = make_comparison_dataframe(LUV, luv3_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_l3, 60).items():
print(err_name, err_value)
cmp_u3 = make_comparison_dataframe(UAL, ual3_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_u3, 60).items():
print(err_name, err_value)
#Data from Feb 03, 2020 to May 28,2020 to check COVID-19 impact
#For running various variations
start_date = '02-03-2020'
end_date = '05-28-2020'
mask = (DAL['ds'] > start_date) & (DAL['ds'] <= end_date)
DAL1 = DAL.loc[mask]
mask = (AAL['ds'] > start_date) & (AAL['ds'] <= end_date)
AAL1 = AAL.loc[mask]
mask = (LUV['ds'] > start_date) & (LUV['ds'] <= end_date)
LUV1 = LUV.loc[mask]
mask = (UAL['ds'] > start_date) & (UAL['ds'] <= end_date)
UAL1 = UAL.loc[mask]
print(DAL1.shape)
print (AAL1.shape)
#DAL1.reset_index(level=0, inplace = True)
DAL1.tail()
plt.figure(figsize = (24,12))
plt.plot(DAL1['ds'],DAL1['y'], 'b-', label = 'Delta')
plt.plot(AAL1['ds'],AAL1['y'], 'r-', label = 'American')
plt.plot(LUV1['ds'],LUV1['y'], 'g-', label = 'SouthWest')
plt.plot(UAL1['ds'],UAL1['y'], 'y-', label = 'United')
#plt.xticks(range(0,DAL.shape[0],500),DAL['Date'].loc[::500],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Market Cap',fontsize=18)
plt.title('Trends in the 4 Airlines Market Cap amidst Covid-19 pandemic')
plt.legend();
plt.figure(figsize = (18,9))
plt.plot(DAL1['ds'],DAL1['y'])
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in Delta Airlines Stocks Prices amidst Covid-19 pandemic')
plt.show()
plt.figure(figsize = (18,9))
plt.plot(AAL1['ds'],AAL1['y'],'r')
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in American Airlines Stocks Prices amidst Covid-19 pandemic')
plt.show()
plt.figure(figsize = (18,9))
plt.plot(LUV1['ds'],LUV1['y'],'g')
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in SouthWest Airlines Stocks Prices amidst Covid-19 pandemic')
plt.show()
plt.figure(figsize = (18,9))
plt.plot(UAL1['ds'],UAL1['y'],'y')
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title('Trends in United Airlines Stocks Prices amidst Covid-19 pandemic')
plt.show()
import logging
logging.getLogger().setLevel(logging.ERROR)
#Covid 19
size = 30
train_df = DAL1[:-size]
D_Model2 = Prophet(changepoint_prior_scale=0.20)
D_Model2.fit(train_df)
train_df = AAL1[:-size]
A_Model2 = Prophet(changepoint_prior_scale=0.20)
A_Model2.fit(train_df)
train_df = LUV1[:-size]
L_Model2 = Prophet(changepoint_prior_scale=0.20)
L_Model2.fit(train_df)
train_df = UAL1[:-size]
U_Model2 = Prophet(changepoint_prior_scale=0.20)
U_Model2.fit(train_df)
##For next 60 days
dal1_forecast = D_Model2.make_future_dataframe(periods=60, freq='D')
# Make predictions
dal1_forecast = dal1_forecast[dal1_forecast['ds'].dt.dayofweek < 5]
dal1_forecast = D_Model2.predict(dal1_forecast)
aal1_forecast = A_Model2.make_future_dataframe(periods=60, freq='D')
# Make predictions
aal1_forecast = aal1_forecast[aal1_forecast['ds'].dt.dayofweek < 5]
aal1_forecast = A_Model2.predict(aal1_forecast)
luv1_forecast = L_Model2.make_future_dataframe(periods=60, freq='D')
# Make predictions
luv1_forecast = luv1_forecast[luv1_forecast['ds'].dt.dayofweek < 5]
luv1_forecast = L_Model2.predict(luv1_forecast)
ual1_forecast = U_Model2.make_future_dataframe(periods=60, freq='D')
# Make predictions
ual1_forecast = ual1_forecast[ual1_forecast['ds'].dt.dayofweek < 5]
ual1_forecast = U_Model2.predict(ual1_forecast)
dal1_forecast.tail(10)
fig5 = go.Figure()
fig5= plot_plotly(D_Model2, dal1_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig5.update_layout(title = 'Market cap forecast of Delta')
D_Model2.plot_components(dal1_forecast)
cmp_df = make_comparison_dataframe(DAL1, dal1_forecast)
cmp_df.tail()
for err_name, err_value in calculate_forecast_errors(cmp_df,60).items():
print(err_name, err_value)
fig6 = go.Figure()
fig6= plot_plotly(A_Model2, aal1_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig6.update_layout(title = 'Market cap forecast of American')
cmp_a1 = make_comparison_dataframe(AAL1, aal1_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_a1, 60).items():
print(err_name, err_value)
fig7 = go.Figure()
fig7= plot_plotly(L_Model2, luv1_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig7.update_layout(title = 'Market cap forecast of Southwest')
cmp_l1 = make_comparison_dataframe(LUV1, luv1_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_l1, 60).items():
print(err_name, err_value)
fig8 = go.Figure()
fig8= plot_plotly(U_Model2, ual1_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig8.update_layout(title = 'Market cap forecast of United')
cmp_a1 = make_comparison_dataframe(UAL1, ual1_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_a1, 60).items():
print(err_name, err_value)
Consider MAPE as it showed less error value when compared with other models Link https://mlcourse.ai/articles/topic9-part2-prophet/
D_Model3 = Prophet(changepoint_prior_scale=0.20)
D_Model3.fit(DAL1)
A_Model3 = Prophet(changepoint_prior_scale=0.20)
A_Model3.fit(AAL1)
L_Model3 = Prophet(changepoint_prior_scale=0.20)
L_Model3.fit(LUV1)
U_Model3 = Prophet(changepoint_prior_scale=0.20)
U_Model3.fit(UAL1)
##For next 60 days
dal2_forecast = D_Model3.make_future_dataframe(periods=60, freq='D')
# Make predictions
dal2_forecast = dal2_forecast[dal2_forecast['ds'].dt.dayofweek < 5]
dal2_forecast = D_Model3.predict(dal2_forecast)
aal2_forecast = A_Model3.make_future_dataframe(periods=60, freq='D')
# Make predictions
aal2_forecast = aal2_forecast[aal2_forecast['ds'].dt.dayofweek < 5]
aal2_forecast = A_Model3.predict(aal2_forecast)
luv2_forecast = L_Model3.make_future_dataframe(periods=60, freq='D')
# Make predictions
luv2_forecast = luv2_forecast[luv2_forecast['ds'].dt.dayofweek < 5]
luv2_forecast = L_Model3.predict(luv2_forecast)
ual2_forecast = U_Model3.make_future_dataframe(periods=60, freq='D')
# Make predictions
ual2_forecast = ual2_forecast[ual2_forecast['ds'].dt.dayofweek < 5]
ual2_forecast = U_Model3.predict(ual2_forecast)
cmp_d2 = make_comparison_dataframe(DAL1, dal2_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_d2, 60).items():
print(err_name, err_value)
cmp_a2 = make_comparison_dataframe(AAL1, aal2_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_a2, 60).items():
print(err_name, err_value)
cmp_l2 = make_comparison_dataframe(LUV1, luv2_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_l2, 60).items():
print(err_name, err_value)
cmp_u2 = make_comparison_dataframe(UAL1, ual2_forecast)
for err_name, err_value in calculate_forecast_errors(cmp_u2, 60).items():
print(err_name, err_value)
fig9 = go.Figure()
fig10 = go.Figure()
fig11 = go.Figure()
fig12 = go.Figure()
fig9 = plot_plotly(D_Model3, dal2_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig9.update_layout(title = 'Market cap forecast of Delta')
fig10 = plot_plotly(A_Model3, aal2_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig10.update_layout(title = 'Market cap forecast of American')
fig11 = plot_plotly(L_Model3, luv2_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig11.update_layout(title = 'Market cap forecast of Southwest')
fig12 = plot_plotly(U_Model3, ual2_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')
fig12.update_layout(title = 'Market cap forecast of United')
U.S. Airlines suspended ALL flights between the U.S. and China On Friday, January 31, Delta, American and United announced they would temporarily suspend all of their mainland China flights in response to the coronavirus outbreak.[14]
Prior to this January 31 announcement:
UNITED AIRLINES on Jan. 28 had announced it would cut 24 flights between the U.S. and China for the first week of February. AMERICAN AIRLINES on Jan. 29 had announced it would suspend flights from Los Angeles to Shanghai and Beijing from Feb. 9 through March 27, 2020. It will maintain its flight schedules (10 daily A/R) from Dallas-Fort Worth to Shanghai and Beijing, as well as from Los Angeles and Dallas-Fort Worth to Hong Kong. DELTA had not adjusted its schedule of direct flights from the U.S. to China. It is the only airline with direct flights to not take action so far.
from fbprophet.diagnostics import cross_validation from fbprophet.diagnostics import performance_metrics
cross_validation_results = cross_validation(D_Model1, initial='3200 days', period='30 days', horizon='70 days') print(cross_validation_results)
performance_metrics_results = performance_metrics(cross_validation_results) print(performance_metrics_results)
#Calculating the highest and lowest spike in the forecasted values
start_date = '2020-05-28'
end_date = '2020-07-27'
mask = (dal2_forecast['ds'] > start_date) & (dal2_forecast['ds'] <= end_date)
dal2_forecast1 = dal2_forecast.loc[mask]
mask = (aal2_forecast['ds'] > start_date) & (aal2_forecast['ds'] <= end_date)
aal2_forecast1 = aal2_forecast.loc[mask]
mask = (luv2_forecast['ds'] > start_date) & (luv2_forecast['ds'] <= end_date)
luv2_forecast1 = luv2_forecast.loc[mask]
mask = (ual2_forecast['ds'] > start_date) & (ual2_forecast['ds'] <= end_date)
ual2_forecast1 = ual2_forecast.loc[mask]
def max_min(df):
max1 = df['yhat'].max()
min1 = df['yhat'].min()
date_of_max = df[df['yhat'] == max1]['ds'].values[0]
date_of_min = df[df['yhat'] == min1]['ds'].values[0]
print ('Max Stock Value in Billion$: ' + str(round(max1,2)) + ' on ' + str(date_of_max))
print ('Min Stock Value in Billion$: ' + str(round(min1,2)) + ' on ' + str(date_of_min))
profit_change = (max1-min1)/min1 * 100
print ('profit change' + str(round(profit_change,2)) + ' %')
return;
max_min(dal2_forecast1)
max_min(luv2_forecast1)
max_min(aal2_forecast1)
max_min(ual2_forecast1)